(function (window, angular, undefined) {
    // 定义安全框架对外接口
    angular.module('security', [])
        .factory('$security', ["$rootScope", function ($rootScope) {
            var $security = {

                // 初始化当前用户和权限信息
                initSecurity: function (needlogin, onUser) {
                    // 应用服务权限
                    $rootScope.si = {};
                    // 菜单权限
                    $rootScope.mi = {};
                    // 当前用户信息
                    $rootScope.curUser = null;

                    var loginUrl = getLoginUrl() + "?service=" + getServiceName();
                    var username = $security.getUrlParam('username');
                    var password = $security.getUrlParam('password');
                    if (username && password) {
                        loginUrl = loginUrl + "&username=" + username + "&password=" + password;
                    }

                    // 获取当前用户信息
                    $security.getUserInfo(
                        function (data, textStatus, xOptions) {
                            $rootScope.$apply(function () {
                                $rootScope.curUser = data.user;
                                if (data.services) {
                                    data.services.forEach(function (e) {
                                        $rootScope.si[e] = true;
                                    });
                                }
                                if (data.menus) {
                                    data.menus.forEach(function (e) {
                                        $rootScope.mi[e] = true;
                                    });
                                }
                            });
                            if (onUser) onUser();
                            if (needlogin && needlogin == true && $rootScope.curUser == null) {
                                window.location.href = loginUrl;
                            }
                        },
                        function (xhr, status, data) {
                            $rootScope.curUser == null;
                            if (needlogin && needlogin == true) {
                                window.location.href = loginUrl;
                            } else {
                                $rootScope.curUser = {};
                                $rootScope.si['sa'] = true;
                                $rootScope.mi['sa'] = true;
                            }
                        }
                    );
                },

                // 确认是否登录
                confirmLogin: function () {
                    var loginUrl = getLoginUrl() + "?service=" + getServiceName();
                    var username = $security.getUrlParam('username');
                    var password = $security.getUrlParam('password');
                    if (username && password) {
                        loginUrl = loginUrl + "&username=" + username + "&password=" + password;
                    }

                    // 获取当前用户信息
                    $security.isLogin(
                        function (data, textStatus, xOptions) {
                            if (data && data == true) {
                                window.location.href = getMainUrl();
                            } else {
                                var ticket = $security.getUrlParam('ticket');
                                if (ticket) {
                                    $security.mklogin(ticket, function (data, textStatus, xOptions) {
                                        // 记录jwt
                                        $.cookie('jwt', data.jwt, { expires: 20 });
                                        window.location.href = getMainUrl();
                                    }, function (xhr, status, data) {
                                        $.messager.alert("系统提示", "登录失败，请确认/sso/mklogin方法是否正常！");
                                    });
                                } else {
                                    window.location.href = loginUrl;
                                }
                            }
                        },
                        function (xhr, status, data) {
                            $.messager.alert("系统提示", "登录失败，请确认/currentuser/isLogin方法是否正常！");
                        }
                    );
                },

                // 模拟登录，解决服务端登录问题
                mklogin: function (ticket, onsuccess, onerror) {
                    jQuery.support.cors = true;
                    $.ajax({
                        url: getServerUrl() + '/sso/mklogin/?ticket=' + ticket,
                        type: 'GET',
                        data: null,
                        timeout: 35000,
                        dataType: 'json',
                        success: onsuccess,
                        error: onerror
                    });
                },

                loginOut: function () {
                    window.location.href = getServerUrl() + "/sso/logout?ticket=" + $.cookie('jwt');
                },

                // 获取当前用户信息
                isLogin: function (onsuccess, onerror) {
                    jQuery.support.cors = true;
                    $.ajax({
                        url: getServerBaseUrl() + '/currentuser/isLogin',
                        headers: { 'jwt': $.cookie('jwt') },
                        type: 'POST',
                        data: null,
                        timeout: 35000,
                        dataType: 'json',
                        success: onsuccess,
                        error: onerror
                    });
                },

                // 获取当前用户信息
                getUserInfo: function (onsuccess, onerror) {
                    jQuery.support.cors = true;
                    $.ajax({
                        url: getServerBaseUrl() + '/currentuser/getUserInfo',
                        headers: { 'jwt': $.cookie('jwt') },
                        type: 'POST',
                        data: null,
                        timeout: 35000,
                        dataType: 'json',
                        success: onsuccess,
                        error: onerror
                    });
                },

                // 设置密码
                setPassword: function (op, np, onsuccess, onerror) {
                    jQuery.support.cors = true;
                    $.ajax({
                        url: getServerBaseUrl() + '/currentuser/setPassword/' + op + '/' + np,
                        headers: { 'jwt': $.cookie('jwt') },
                        type: 'POST',
                        data: null,
                        timeout: 35000,
                        dataType: 'json',
                        success: onsuccess,
                        error: onerror
                    });
                },

                getUrlParam: function (name) {
                    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                    var r = window.location.search.substr(1).match(reg);
                    if (r != null) return unescape(r[2]);
                    return null;
                },

                /**
                 * 获取cpu位数
                 */
                getCPU: function () {
                    var agent = navigator.userAgent.toLowerCase();
                    if (agent.indexOf("win64") >= 0 || agent.indexOf("wow64") >= 0) return "x64";
                    return navigator.cpuClass;
                },

				/**
				 * 获取浏览器版本
				 */
                getBrowserVersion: function () {
                    var UserAgent = navigator.userAgent.toLowerCase();
                    return {
                        isUc: /ucweb/.test(UserAgent), // UC浏览器
                        isChrome: /chrome/.test(UserAgent.substr(-33, 6)), // Chrome浏览器
                        isFirefox: /firefox/.test(UserAgent), // 火狐浏览器
                        isOpera: /opera/.test(UserAgent),  // Opera浏览器
                        isSafire: /safari/.test(UserAgent) && !/chrome/.test(UserAgent), // safire浏览器
                        is360: /360se/.test(UserAgent), // 360浏览器
                        isBaidu: /bidubrowser/.test(UserAgent), // 百度浏览器
                        isSougou: /metasr/.test(UserAgent), // 搜狗浏览器
                        isIE6: /msie 6.0/.test(UserAgent), // IE6
                        isIE7: /msie 7.0/.test(UserAgent), // IE7
                        isIE8: /msie 8.0/.test(UserAgent), // IE8
                        isIE9: /msie 9.0/.test(UserAgent), // IE9
                        isIE10: /msie 10.0/.test(UserAgent), // IE10
                        isIE11: /msie 11.0/.test(UserAgent), // IE11
                        isLB: /lbbrowser/.test(UserAgent), // 猎豹浏览器
                        isWX: /micromessenger/.test(UserAgent), // 微信内置浏览器
                        isQQ: /qqbrowser/.test(UserAgent) // QQ浏览器
                    };
                },

				/**
				 * 获取操作系统版本
				 */
                getOs: function () {
                    var UserAgent = navigator.userAgent.toLowerCase();
                    return {
                        isIpad: /ipad/.test(UserAgent),
                        isIphone: /iphone os/.test(UserAgent),
                        isAndroid: /android/.test(UserAgent),
                        isWindowsCe: /windows ce/.test(UserAgent),
                        isWindowsMobile: /windows mobile/.test(UserAgent),
                        isWin2K: /windows nt 5.0/.test(UserAgent),
                        isXP: /windows nt 5.1/.test(UserAgent),
                        isVista: /windows nt 6.0/.test(UserAgent),
                        isWin7: /windows nt 6.1/.test(UserAgent),
                        isWin8: /windows nt 6.2/.test(UserAgent),
                        isWin81: /windows nt 6.3/.test(UserAgent),
                        isMac: /mac os/.test(UserAgent)
                    };
                },

                confirmBrowser: function () {
                    var version = $security.getBrowserVersion();

                    if (version.isIE6 || version.isIE7 || version.isIE8) {

                        var os = $security.getOs();
                        if (os.isXP || os.isVista) {
                            $rootScope.onlyChrome = true;
                        } else {
                            $rootScope.onlyChrome = false;
                        }

                        var banben = $security.getCPU();
                        if ("x64" == banben) {
                            $rootScope.only64 = true;
                        } else {
                            $rootScope.only32 = true;
                        }
                        return false;
                    }
                    return true;
                }
            };
            for (f in $security) {
                $rootScope[f] = $security[f];
            }
            return $security;
        }])
        .controller('loginCtrl', ['$rootScope', '$scope', '$security',
            function ($rootScope, $scope, $security) {
            }
        ])
        .run(["$rootScope", "$security", function ($rootScope, $security) {
        }]);
}(window, angular));